<template>
  <div>
    <!-- <div class="tools-div">
        <el-button type="success" size="small" @click="importExcel">
          导 入
        </el-button>
        <el-button type="primary" size="small" @click="outputExcel">
          导 出
        </el-button>
        <hr/>
      </div>  -->
    <div style="background:#FFF;padding:5px;">
      <el-button
        type="primary"
        size="small"
        @click="dialogImportVisible = true"
      >
        导入
      </el-button>
      <el-button type="success" size="small" @click="hanldeExport">
        导出
      </el-button>
    </div>

    <!-- 导入excel文件的对话框 -->
    <div>
      <el-dialog v-model="dialogImportVisible" title="导入" width="30%">
        <el-form label-width="120px">
          <el-form-item label="分类文件">
            <el-upload
              class="upload-demo"
              :action="uploadPath"
              name="excel"
              :on-success="onUploadSuccess"
              :headers="headers"
            >
              <el-button type="primary">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-table
        :data="list"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="imageUrl" label="图标" #default="scope">
          <img
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            style="width:40px;height:40px"
          />
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" />
        <el-table-column prop="status" label="状态" #default="scope">
          {{ scope.row.status === 1 ? '正常' : '不显示' }}
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="Operations">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增/更新菜单的弹窗 -->
    <div>
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
        <el-form label-width="120px">
          <el-form-item label="分类名称">
            <el-input v-model="category.name" />
          </el-form-item>
          <el-form-item label="图标" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :headers="headers"
              name="file"
              :data="{ module: 'avatar' }"
            >
              <img
                v-if="category.imageUrl"
                :src="category.imageUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="category.orderNum" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="category.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="UpdateCategory">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  GetCategoriesByPid,
  DeleteCategoryById,
  GetCategoryById,
  UpdateCategoryById,
  ExportCatesExcel,
} from '@/api/category'
import { useApp } from '@/pinia/modules/app'
onMounted(() => {
  fetchData(0)
})

const uploadPath = 'http://localhost:8501/admin/product/category/import'
const headers = { token: useApp().authorization.token }

//表格需要的数据和函数
const list = ref([])
const load = async (row, treeNode, resolve) => {
  //row代表点击按钮所在行的json对象: row.id
  //resolve可以将加载到的数据列表渲染到点击按钮行的下面
  //   console.log(row, treeNode, resolve)
  const { data } = await GetCategoriesByPid(row.id)
  resolve(data)
}

const handleDelete = row => {
  ElMessageBox.confirm(`正在删除角色【${row.name}】 ,是否确认？`, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await DeleteCategoryById(row.id)
      if (+code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新页面数据
        fetchData(0)
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const dialogTitle = ref('更新菜单')
const dialogVisible = ref(false)
const category = ref({})
const handleEdit = async row => {
  const { data } = await GetCategoryById(row.id)
  console.log(data)
  category.value = data
  dialogVisible.value = true
}

const UpdateCategory = async () => {
  await UpdateCategoryById(category.value)
  ElMessage.success('修改成功')
  dialogVisible.value = false
  fetchData(0)
}

const dialogImportVisible = ref(false)

const onUploadSuccess = (response, uploadFile) => {
  if (+response.code === 200) {
    ElMessage.success('导入成功')
    fetchData(0)
  } else {
    ElMessage.success(response.message)
  }

  dialogImportVisible.value = false
}

const hanldeExport = () => {
  ExportCatesExcel().then(res => {
    const blob = new Blob([res])

    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '分类数据.xlsx'
    //模拟点击下载链接
    link.click()
  })
}

const fetchData = async pid => {
  const { data } = await GetCategoriesByPid(pid)
  list.value = data
}
</script>
